package com.link4a.doms.dao;

import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author brown
 */
public abstract class SqlSessionTemplateSupport {

	private EnumMap<ExecutorType, SqlSessionTemplate> sqlSessionTemplates = new EnumMap<>(ExecutorType.class);
	private EnumMap<ExecutorType, NamespaceSqlSession> namespaceSqlSessions = new EnumMap<>(ExecutorType.class);
	
	@Autowired
	public void setSqlSessionTemplates(List<SqlSessionTemplate> SqlSessionTemplates) {
		for (SqlSessionTemplate template : SqlSessionTemplates) {
			sqlSessionTemplates.put(template.getExecutorType(), template);
			
			NamespaceSqlSession namespaceSqlSession = new NamespaceSqlSession(template, getClass().getName());
			namespaceSqlSessions.put(template.getExecutorType(), namespaceSqlSession);
		}
	}
	
	public SqlSession getSqlSession() {
		return namespaceSqlSessions.get(ExecutorType.BATCH);
//		return namespaceSqlSessions.get(ExecutorType.REUSE);
	}
//	
//	public SqlSession getBatchSqlSession() {
//		return namespaceSqlSessions.get(ExecutorType.BATCH);
//	}

	protected final <E> Page<E> findPage(Condition condition, String countStatementId, String queryStatementId) {
		int rowCount = getSqlSession().selectOne(countStatementId, condition);
		Collection<E> rows = Collections.emptyList();
		if (rowCount != 0) {
			rows = getSqlSession().selectList(queryStatementId, condition);
		}
		return new Page<>(rows, rowCount, condition);
	}

	protected final <E> Page<E> findPage(Condition condition, String countStatementId, String queryPKStatementId, String queryStatementId) {
		int rowCount = getSqlSession().selectOne(countStatementId, condition);
		Collection<E> rows = Collections.emptyList();
		if (rowCount != 0) {
			condition.setIds(getSqlSession().selectList(queryPKStatementId, condition));
			rows = getSqlSession().selectList(queryStatementId, condition);
		}
		return new Page<>(rows, rowCount, condition);
	}

}
